<template>
    <el-dialog v-model="show" :title="title" :close-on-press-escape="false" :close-on-click-modal="false"
        :show-close="false" :draggable="true" @before-close="() => false" append-to-body style="width: 50%;">
        <FormBase :mode="mode" @on-submit="onSubmit" @on-cancel="handleClose">
            <div class="editor-container">
                <el-tabs type="border-card" v-model="activeName">
                    <el-tab-pane label="基础信息" name="1">
                        <el-form ref="topicForm" :model="dataModel" label-width="auto" :rules="rules"
                            style="width:100%">
                            <el-form-item :label="t('专题名称')" prop="name">
                                <el-input v-model="dataModel.name" :disabled="mode === 'view'" />
                            </el-form-item>
                            <el-form-item :label="t('专题分类')" prop="categoryId">
                                <el-select v-model="dataModel.categoryId" :placeholder="t('请选择')">
                                    <el-option v-for="item in categoryOptions" :key="item.value" :label="item.label"
                                        :value="item.value" :disabled="mode === 'view'" />
                                </el-select>
                            </el-form-item>
                            <el-form-item :label="t('专题介绍')" prop="description">
                                <el-input type="textarea" v-model="dataModel.description" :rows="5"
                                    :disabled="mode === 'view'" />
                            </el-form-item>
                            <el-form-item :label="t('专题封面')" prop="originImg">
                                <VImage ref="uploadImage" :src="dataModel.originImg" :autoUpload="false"
                                    :style="{ height: '160px', width: '160px' }" fit="contain"
                                    :disabled="mode === 'view'">
                                </VImage>
                            </el-form-item>
                        </el-form>
                    </el-tab-pane>
                    <el-tab-pane label="课程" name="2">
                        <div style="padding: 0 0 10px 0;">
                            <el-button type="primary" @click="handleAddCourse">{{ t('添加')
                                }}</el-button>
                            <el-button type="default" @click="handleRemoveCourse">{{ t('移除')
                                }}</el-button>
                        </div>
                        <el-table ref="courseTableRef" :data="tableDataCourse" :border="true"
                            header-row-class-name="table-header" height="400">
                            <el-table-column type="selection" width="55" />
                            <el-table-column prop="name" :label="t('名称')" width="180" />
                            <el-table-column prop="categoryText" :label="t('分类')" width="180" />
                            <el-table-column prop="originImg" :label="t('封面')">
                                <template #default="scope">
                                    <v-image :src="scope.row.originImg" :style="{ width: '45px', height: '45px' }"
                                        :disabled="true"></v-image>
                                </template>
                            </el-table-column>
                            <el-table-column prop="likes" :label="t('点赞数')">
                            </el-table-column>
                            <el-table-column prop="joins" :label="t('学习人数')">
                            </el-table-column>
                        </el-table>
                    </el-tab-pane>
                </el-tabs>
            </div>
        </FormBase>

        <CourseSelect v-model:show="showCourseSelection" v-model="dataModel.courseIds"
            @on-selected="handleCourseSelected">
        </CourseSelect>
    </el-dialog>
</template>
<script setup lang="ts">
import { Ref, computed, onMounted, onUnmounted, reactive, ref, watch } from 'vue';
import { t } from '@/common/locale';
import { FormRules } from 'element-plus';
import { add, getTopicCourses, getTopicDetail, update } from '@/api/topic';
import elHelper from '@/common/elHelper';
import { getCategoryOptions } from '@/api/category';
import VImage from '@/components/other/VImage.vue'
import comFunc from '@/common/comFunc';
import CourseSelect from '@/components/course/CourseSelect.vue';
import FormBase from '../layout/FormBase.vue';

const props = defineProps({
    data: {
        type: Object,
        default: {}
    },
    mode: {
        type: String,
        validator: (val: string) => {
            return ['add', 'modify'].includes(val)
        },
        default: 'add'
    }
})
const show = defineModel('show', { type: Boolean })

const emit = defineEmits(['onSubmited'])
const title = computed(() => {
    switch (props.mode) {
        case 'add':
            return t('新增')
        case 'modify':
            return t('修改')
        case 'view':
            return t('查看')
    }
})

const dataModel: TopicDataModel = reactive({
    name: '',
    desc: '',
    categoryId: '',
    title: '',
    originImg: '',
    objectId: '',
    thumbImg: '',
    courseIds: []
})
Object.assign(dataModel, props.data)
const mode = ref(props.mode)
const activeName = ref('1')
const dialogTableVisible = ref(false)
const courseTableRef = ref()
const topicForm = ref()
const uploadImage = ref()
const categoryOptions: Ref<CategorySelectOption[]> = ref([])
const tableDataCourse: Ref<CourseDataModel[]> = ref([])
const showCourseSelection = ref(false)
const rules = reactive<FormRules<TopicDataModel>>({
    name: [
        { required: true, message: t('请输入专题名称'), trigger: 'blur' }
    ],
    categoryId: [
        { required: true, message: t('请选择专题分类'), trigger: 'blur' }
    ],

})
watch(() => show.value, async (val) => {
    if (val) {
        Object.assign(dataModel, props.data)
        mode.value = props.mode
        await getInfo()
        getCourseData()
    } else {
        dataModel.description = ''
        dataModel.name = ''
        dataModel.objectId = ''
        dataModel.originImg = ''
        dataModel.thumbImg = ''
        dataModel.categoryId = ''
        dataModel.courseIds = []
        uploadImage.value?.clear()

    }
})
const onSubmit = async () => {
    let valid = await topicForm.value.validate((valid) => valid)
    if (valid) {
        const loading = elHelper.showLoading()
        const reUpload = await uploadImage.value?.upload()
        if (!reUpload.isSuccess) {
            elHelper.showErrorMsg(reUpload.msg)
            return
        }
        dataModel.originImg = reUpload.path
        dataModel.courseIds = []
        tableDataCourse.value.forEach(item => {
            dataModel.courseIds?.push(comFunc.nvl(item.objectId))
        })
        if (mode.value === 'add') {
            const re = await add(dataModel)
            if (re.isSuccess) {
                emit('onSubmited', re.data!)
                elHelper.showSuccessMsg('操作成功')
                handleClose()
            } else {
                elHelper.showErrorMsg(re.msg)
            }
        } else {
            const re = await update(dataModel)
            if (re.isSuccess) {
                emit('onSubmited', re.data!)
                elHelper.showSuccessMsg('操作成功')
                handleClose()
            } else {
                elHelper.showErrorMsg(re.msg)
            }
        }
        elHelper.closeLoading(loading)
    }
}
const handleClose = () => {
    show.value = false
}
const getInfo = async () => {
    const re = await getTopicDetail(comFunc.nvl(dataModel.objectId))
    if (re.isSuccess) {
        Object.assign(dataModel, re.data)
    }
}
const getCourseData = async () => {
    tableDataCourse.value = []
    const re = await getTopicCourses(comFunc.nvl(dataModel.objectId))
    if (re.isSuccess) {
        tableDataCourse.value = re.data as CourseDataModel[]
    }
}
const handleAddCourse = () => {
    showCourseSelection.value = true
}
const handleRemoveCourse = () => {
    if (!courseTableRef.value) return
    const rows = courseTableRef.value.getSelectionRows()
    if (rows.length <= 0) {
        elHelper.showErrorMsg('请选择要移除的课程')
        return
    }
    rows.forEach((r) => {
        const index = tableDataCourse.value.findIndex(v => v.objectId === r.objectId)
        if (index >= 0) tableDataCourse.value.splice(index, 1)
        const indexOfCourseIds = dataModel.courseIds?.findIndex(v => v === r.objectId) as number
        if (indexOfCourseIds >= 0) dataModel.courseIds?.splice(indexOfCourseIds, 1)
    })
}
const handleCourseSelected = (val: CourseDataModel[]) => {
    val.forEach((item) => {
        if (!tableDataCourse.value.find(v => v.objectId === item.objectId)) {
            tableDataCourse.value.push(item)
        }
    })
}
onMounted(async () => {
    const l = await getCategoryOptions('TOPIC')
    categoryOptions.value = l
})
onUnmounted(() => {
    handleClose()
})
</script>
<style lang="scss" scoped>
.editor-container {
    width: 100%;
}

.btn-container {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 10px 0 0 0;
}
</style>